<?php

namespace ImWorker;

/**
 * 日志操作类
 * @author YeWJ <yeweijian299@163.com>
 * @time 2016-07-18 10:03:07
 */
class Log
{
    const LOG_NONE = 0;
    const LOG_ECHO = 1;
    const LOG_FILE = 2;

    private $config;

    public function __construct(Config $config)
    {
        $this->config = $config;
    }

    public function logNone($msg)
    {
        return;
    }

    public function logEcho($msg)
    {
        return $this->save($msg, self::LOG_ECHO);
    }

    public function logFile($msg, $dirname = null)
    {
        return $this->save($msg, self::LOG_FILE, $dirname);
    }

    private function save($msg, $type = 1, $dirname = null)
    {
        $now  = date($this->config->get('log.timeFormat', 'Y-m-d H:i:s'));
        $info = "{$msg}\r\n";
        switch ($type) {
            case self::LOG_ECHO:
                echo $info;
                break;
            case self::LOG_FILE:
                $path = $this->config->get('log.path', LOGSPATH);
                if ($dirname) {
                    $path .= DS . $dirname;
                }
                $destination = $path . DS . date('y_m_d') . '.log';

                !is_dir($path) && mkdir($path, 0755, true);

                //检测日志文件大小，超过配置大小则备份日志文件重新生成
                if (is_file($destination) && floor($this->config->get('log.fileSize', 1024 * 1024 * 10)) <= filesize($destination)) {
                    rename($destination, dirname($destination) . DS . time() . '-' . basename($destination));
                }

                return error_log("[{$now}] " . $info, 3, $destination);
            default:
                # code...
                break;
        }
        return;
    }
}
